layui.use(['form','layer','table','laytpl','authtree'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var authtree = layui.authtree;

    //角色列表
    var tableIns = table.render({
        elem: '#tablelist',
        url : '/role',
        type:"GET",
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 20,
        id : "roleListTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'name', title: '权限名称', minWidth:100, align:"center"},
            {field: 'useable', title: '是否可用', minWidth:200, align:'center',
                templet:function(d){
                    return d.useable == 0? "已启用": "已禁用";
                }
            },
            {field: 'remarks', title: '备注', align:'center'},
            {field: 'createDate', title: '创建时间', align:'center',minWidth:150,sort:true,
                templet:function(d){
                    //处理时间
                    var date = new Date(d.createDate);
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                }
            },
            {title: '操作', minWidth:175, templet:'#listBar',fixed:"right",align:"center"}
        ]]
    });

    //搜索
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    
    //添加角色
    function addRole(edit){
        var index = layui.layer.open({
            title : "添加角色",
            type : 2,
            content : "roleAdd",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                if(edit){
                    //角色信息
                    body.find("#name").val(edit.name);
                    //查询角色权限
                    $.get('/role/' + edit.id,function (data) {
                        $.each(data.menuIds,function (i, ele) {
                            body.find('input[value=' + ele + ']').prop('checked', 'checked');
                        });
                    });
                    form.render();
                    authtree.checkAll('#LAY-auth-tree-index');
                    console.log(body);
                    var inputs = $(body.children()[0]).find('input');
                    /*var data = [];
                    inputs.each(function(index, item){
                        data.push(item.value);
                    });*/
                    console.log(inputs);
                }
                setTimeout(function(){
                    layui.layer.tips('点击此处返回角色列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        })
    }
    $(".addBtn").click(function(){
        addRole();
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('roleListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的角色？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的角色");
        }
    });

    //列表操作
    table.on('tool(roleList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "修改角色信息",
                type : 2,
                content : "roleEdit?id=" + data.id,
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回角色列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            })
            /*addRole(data);*/
        }else if(layEvent === 'usable'){ //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此角色？",
                btnText = "已禁用";
            if(_this.text()=="已禁用"){
                usableText = "是否确定启用此角色？",
                btnText = "已启用";
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
                _this.text(btnText);
                layer.close(index);
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此角色？',{icon:3, title:'提示信息'},function(index){
                //TODO
                $.delete("/role/" + data.id,function (data) {
                    if (data.code == 200) {
                        top.layer.msg("删除成功！");
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        top.layer.msg("删除失败！");
                    }
                });

            });
        }
    });

});